package com.lwlk.demo.dao;

import com.lwlk.demo.entity.UserEntity;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Repository;

import javax.persistence.EntityManager;
import javax.persistence.TypedQuery;
import javax.persistence.criteria.CriteriaBuilder;
import javax.persistence.criteria.CriteriaQuery;
import javax.persistence.criteria.Root;
import java.util.List;

@Repository
public class UserDao {

    private final EntityManager entityManager;

    @Autowired
    public UserDao(EntityManager entityManager) {

        this.entityManager = entityManager;
    }

    public List<UserEntity> findByHql(String name) {

        TypedQuery<UserEntity> query = entityManager.createQuery("select u from UserEntity u where u.name like :name", UserEntity.class);

        query.setParameter("name", "%" + name + "%");

        return query.getResultList();
    }

    public List<UserEntity> findByCr() {

        CriteriaBuilder builder = entityManager.getCriteriaBuilder();

        CriteriaQuery<UserEntity> query = builder.createQuery(UserEntity.class);

        Root<UserEntity> root = query.from(UserEntity.class);

        query.where(builder.like(root.get("name"), "___"));

        return entityManager.createQuery(query).getResultList();
    }
}
